package com.feng.system.controller;

import com.feng.common.api.ResponseResult;
import com.feng.common.validation.groups.Update;
import com.feng.system.dto.PermissionParam;
import com.feng.system.service.PermissionService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;
import java.util.Set;

/**
 * @author Feng
 * @since 2022/4/20 18:20
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    PermissionService permissionService;

    @ApiOperation("获取所有权限")
    @GetMapping
    @PreAuthorize("@er.check('perm:list')")
    public ResponseResult all() {
        return ResponseResult.success(permissionService.getAllPermissions());
    }

    @ApiOperation("添加单个权限")
    @PostMapping
    @PreAuthorize("@er.check('perm:add')")
    public ResponseResult add(@RequestBody @Validated PermissionParam param) {
        permissionService.addPermission(param.getName(), param.getKey());
        return ResponseResult.success();
    }

    @ApiOperation("修改单个权限")
    @PutMapping
    @PreAuthorize("@er.check('perm:update')")
    public ResponseResult update(@RequestBody @Validated({Default.class, Update.class}) PermissionParam param) {
        permissionService.updatePermission(param.getId(), param.getName(), param.getKey());
        return ResponseResult.success();
    }

    @ApiOperation("删除权限")
    @DeleteMapping
    @PreAuthorize("@er.check('perm:delete')")
    public ResponseResult delete(@RequestBody Set<Long> ids) {
        permissionService.deletePermissionByIds(ids);
        return ResponseResult.success();
    }

}
